<template>
  <div class="center">
    <div class="step">
      <el-steps style="width: 600px" :active="active" finish-status="success" align-center>
        <el-step title="Step 1" description="安装指定微信版本" />
        <el-step title="Step 2" description="完成登录微信" />
        <el-step title="Step 3" description="通过" />
      </el-steps>
    </div>
    <div class="align" v-if="showVersionTip">
      <div style="width: 500px;">
        <el-row style="margin-bottom: 15px;">
          <el-col :span="24"><el-alert :title="errorAlert" type="error" :closable="false" /></el-col>
        </el-row>
        <el-row style="margin-bottom: 15px;" :gutter="20">
          <el-col :span="12">
            <el-select v-model="selectedVersion" placeholder="请选择版本">
              <el-option v-for="version in versions" :key="version" :label="version" :value="version"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="success" @click="downloadWx" :disabled="downloading">
              <el-icon :size="20">
                <Download />
              </el-icon>下载
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="danger" @click="cancelDownloadWx">
              取消
            </el-button>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 15px;" :gutter="20">
          <el-col :span="20">
            <el-progress :stroke-width="8" :percentage="progress" :indeterminate="true" />
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="align" v-if="showLoginTip">
      <div style="width: 500px;">
        <el-row style="margin-bottom: 15px;" :gutter="20">
          <el-col :span="20"><el-alert :title="errorAlert" type="error" :closable="false" /></el-col>
          <el-col :span="4" style="line-height: 32px;">
            <el-button type="success" @click="openWx">
              启动
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="align">
      <!-- <div style="width: 500px;"> -->
      <el-button type="primary" @click="checkWx">重新检测</el-button>
      <!-- </div> -->
    </div>
  </div>
</template>

<script>
import WinControl from "@/components/WinControl/index.vue";
import { Download } from '@element-plus/icons-vue';
import { checkLogin } from '@/api/wxauto'
import { ElMessage, ElLoading } from 'element-plus';
import axios from 'axios';

export default {
  name: 'Hook',
  data() {
    return {
      versions: [
        '3.9.11.25'
      ],
      currentVersion: '',
      selectedVersion: '',

      errorAlert: '',
      showVersionTip: false,
      showLoginTip: false,

      active: 0,
      downloading: false,
      progress: 0,
      controller: new AbortController(), // 添加控制器
    };
  },
  components: {
    WinControl,
    Download,
  },
  computed: {
  },
  mounted() {
    this.checkWx()
  },
  methods: {
    async checkWx() {
      this.reset()
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      if (! await this.checkWxVersion()) {
        loading.close()
        return;
      }
      if (! await this.checkWxLogin()) {
        loading.close()
        return;
      }
      this.pass()
      loading.close()
    },

    async checkWxVersion() {
      try {
        const version = await window.electronAPI.getWxVersion()
        console.log(this.versions.includes(version))
        if (!this.versions.includes(version)) {
          this.showVersionTip = true
          this.errorAlert = `当前版本：${version} 无法适配，请安装指定版本`
          return false;
        }
        this.currentVersion = version
        this.active = 1
        return true;
      } catch (error) {
        this.showVersionTip = true
        this.errorAlert = "没有安装微信，请安装指定版本"
        return false
      }
    },

    async checkWxLogin() {
      const command = await window.electronAPI.hookWx(this.currentVersion)
      let isLogin = await checkLogin()
      if (!isLogin) {
        this.showLoginTip = true
        this.errorAlert = "需要以【管理员权限】运行微信"
        return false
      }
      this.active = 2
      return true
    },

    openWx() {
      window.electronAPI.openWx()
    },

    downloadWx() {
      if (this.selectedVersion === '') {
        ElMessage.error('请选择指定版本');
        return;
      }
      this.downloading = true
      axios({
        url: `https://43.136.97.12:8443/wechat-windows-versions/WeChatSetup-${this.selectedVersion}.exe`, // 下载
        method: 'GET',
        responseType: 'blob', // 确保响应类型为 blob
        onDownloadProgress: progressEvent => {
          this.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        },
        signal: this.controller.signal
      }).then(response => {
        // 创建一个 URL 对象，表示要下载的文件
        const url = window.URL.createObjectURL(new Blob([response.data]));
        // 创建一个 <a> 元素，用于触发下载
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `WeChatSetup-${this.selectedVersion}.exe`); // 替换为实际的文件名和扩展名
        document.body.appendChild(link);
        link.click();
        // 下载完成后，移除 <a> 元素
        document.body.removeChild(link);
        // 释放 URL 对象
        window.URL.revokeObjectURL(url);
        this.progress = 0; // 重置进度条
        this.downloading = false
      }).catch(error => {
        ElMessage.error('下载文件时出错');
        // console.error('下载文件时出错：', error);
        setTimeout(() => {
          this.progress = 0; // 出错时也重置进度条
          this.downloading = false
        }, 500)
      });
    },

    cancelDownloadWx() {
      this.controller.abort(); // 取消下载
      this.controller = new AbortController(); // 重置控制器，以便下次下载
    },

    pass() {
      this.active = 3
      this.$store.commit("initInfo");
      ElMessage.success('检验成功')
    },

    reset() {
      this.errorAlert = ''
      this.showVersionTip = false
      this.showLoginTip = false
      if (this.downloading) {
        cancelDownloadWx()
      }
    },
  },
};
</script>
<style>
.center {
  width: calc(100vw - 68px);
  height: calc(100vh - 36px);
}

.step {
  display: flex;
  justify-content: center;
  margin: 80px 0;
}

.align {
  display: flex;
  justify-content: center;
}

.opt {
  display: flex;
  justify-content: center;
}
</style>